package com.nulstudio.sppm.service;

import com.nulstudio.sppm.config.NulSecurityConfig;
import com.nulstudio.sppm.domain.vo.PersonalInformationVo;
import com.nulstudio.sppm.entity.NulUserDetail;
import com.nulstudio.sppm.exception.NulException;
import com.nulstudio.sppm.exception.NulExceptionConstants;
import com.nulstudio.sppm.mapper.PersonalInformationMapper;
import jakarta.annotation.Resource;
import org.springframework.lang.NonNull;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public final class PersonalInformationService {

    @Resource @NonNull
    private PersonalInformationMapper personalInformationMapper;

    @NonNull
    public PersonalInformationVo getCurrentPersonalInformation() {
        final NulUserDetail userDetail = NulSecurityConfig.getContextUserDetail();
        final int uid = userDetail.getUid();
        final PersonalInformationVo personalInformationVo = personalInformationMapper.selectPersonalInformationById(uid);
        if (personalInformationVo == null) {
            throw new NulException(NulExceptionConstants.USER_NOT_EXIST);
        }
        return personalInformationVo;
    }

    public void updateCurrentPersonalInformation(@NonNull String name, int gender) {
        final NulUserDetail userDetail = NulSecurityConfig.getContextUserDetail();
        final int uid = userDetail.getUid();
        if (gender <= 0 || gender > 2) {
            throw new NulException(NulExceptionConstants.INVALID_GENDER);
        }
        final int result = personalInformationMapper.updatePersonalInformationById(uid, name, gender);
        if (result <= 0) {
            throw new NulException(NulExceptionConstants.USER_NOT_EXIST);
        }
    }

    public void updateCurrentPassword(@NonNull String password) {
        final NulUserDetail userDetail = NulSecurityConfig.getContextUserDetail();
        final int uid = userDetail.getUid();
        final String encryptedPassword = new BCryptPasswordEncoder().encode(password);
        final int result = personalInformationMapper.updatePasswordById(uid, encryptedPassword);
        if (result <= 0) {
            throw new NulException(NulExceptionConstants.USER_NOT_EXIST);
        }
    }

}
